package meijuli.com.join51.business.fragment;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import meijuli.com.join51.business.R;
import meijuli.com.join51.business.activity.AddCommodityActivity;
import meijuli.com.join51.business.activity.ClassificationActivity;
import meijuli.com.join51.business.adapter.ClassificationAdapter;
import com.jhx.common.http.ApiManager;
import com.jhx.common.http.HttpRequest;
import com.jhx.common.http.HttpResponse;
import com.jhx.common.http.ResponseCallback;
import meijuli.com.join51.business.model.Category;
import com.jhx.common.model.Event;
import com.jhx.common.model.EventBean;
import com.jhx.common.widget.CommonDialog;

import meijuli.com.join51.business.service.ApiService;
import meijuli.com.join51.business.ui.OneKeyDeleteEditView;
import meijuli.com.join51.business.utils.SoftInputUtil;
import com.jhx.common.utils.ToastUtil;
import retrofit2.Call;

/**
 * 分类页面
 *
 * @author wenqin 2017-04-25 13:59
 */

public class ClassificationFragment extends BaseFragment implements ClassificationActivity.OnMenuTextClick,
        ClassificationAdapter.OnEditClickListener, ClassificationAdapter.OnCheckChangedListener {

    //分类开启状态
    public static final int STATUS_OPEN = 1;
    public static final int STATUS_CLOSE = 0;
    RecyclerView mClassificationRecycler;
    RecyclerView mClassificationCloseRecycler;
    TextView mTitleOpen;
    TextView mTitleClose;
    private List<Category> mCategoryList;
    private List<Category> mCloseCategoryList;
    private ClassificationAdapter mAdapter;
    private ClassificationAdapter mCloseAdapter;
    private Call<HttpResponse<String>> mCall;
    private String formPage = "";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_classification, container, false);
        mClassificationRecycler = view.findViewById(R.id.classification_recycler);
        mClassificationCloseRecycler = view.findViewById(R.id.classification_close_recycler);
        mTitleOpen = view.findViewById(R.id.title_open);
        mTitleClose = view.findViewById(R.id.title_close);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        ClassificationActivity activity = (ClassificationActivity) getActivity();
        activity.setOnMenuTextClick(this);

        initRecyclerView();

        requestCategoryList();
        formPage = getArguments().getString(ClassificationActivity.KEY_FORM);
    }

    public static ClassificationFragment newInstance(String formPage) {
        ClassificationFragment fragment = new ClassificationFragment();
        Bundle bundle = new Bundle();
        bundle.putString(ClassificationActivity.KEY_FORM, formPage);
        fragment.setArguments(bundle);
        return fragment;
    }

    private void requestCategoryList() {
        showLoadingDialog();
        Call<HttpResponse<List<Category>>> call = ApiManager.get().getApiService(ApiService.class).getCategoryList(
                new HashMap<String, String>());
        HttpRequest.getRequest().autoRecycle(this).start(call, new ResponseCallback() {
            @Override
            public void onSuccess(String url, Object data) {
                dismissDialog();
                mCategoryList.clear();
                mCloseCategoryList.clear();
                List<Category> categoryList = (List<Category>) data;
                for (int i = 0; i < categoryList.size(); i++) {
                    if (categoryList.get(i).getStatus() == Category.STATUS_OPEN) {
                        mCategoryList.add(categoryList.get(i));
                    } else {
                        mCloseCategoryList.add(categoryList.get(i));
                    }
                }
                EventBus.getDefault().post(new EventBean<>(EventBean.STATUS_NEW_CATEGORY));

                mAdapter.notifyDataSetChanged();
                mCloseAdapter.notifyDataSetChanged();
                mAdapter.setOnCheckChangedListener(ClassificationFragment.this);
                mCloseAdapter.setOnCheckChangedListener(ClassificationFragment.this);
                setSize();
            }

            @Override
            public void onError(String url, int errorCode, String errorMsg) {
                super.onError(url, errorCode, errorMsg);
                dismissDialog();
            }
        });

    }

    private void initRecyclerView() {
        mCategoryList = new ArrayList<>();
        mCloseCategoryList = new ArrayList<>();

        mAdapter = new ClassificationAdapter(getActivity(), mCategoryList);
        mCloseAdapter = new ClassificationAdapter(getActivity(), mCloseCategoryList);
        mClassificationRecycler.setLayoutManager(new LinearLayoutManager(getActivity()));
        mClassificationCloseRecycler.setLayoutManager(new LinearLayoutManager(getActivity()));
        mClassificationCloseRecycler.setNestedScrollingEnabled(false);
        mClassificationRecycler.setNestedScrollingEnabled(false);
        mClassificationCloseRecycler.setAdapter(mCloseAdapter);
        mClassificationRecycler.setAdapter(mAdapter);

        mAdapter.setOnEditClickListener(this);
        mCloseAdapter.setOnEditClickListener(this);
        mAdapter.setOnItemClickListener(new ClassificationAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (TextUtils.isEmpty(formPage) || !formPage.equals(AddCommodityActivity.class.getName())) {
                    return;
                }
                Category category = mCategoryList.get(position);
                Event event = new Event();
                event.setData(category);
                EventBus.getDefault().post(event);
                getActivity().finish();
            }
        });

        mCloseAdapter.setOnItemClickListener(new ClassificationAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, final int position) {
                if (TextUtils.isEmpty(formPage) || !formPage.equals(AddCommodityActivity.class.getName())) {
                    return;
                }
                CommonDialog dialog = new CommonDialog(getActivity());
                dialog.setMessage("当前分类是关闭状态，确定要打开该分类嘛？");
                dialog.setOnClickListener(new CommonDialog.OnClickListener() {
                    @Override
                    public void onConfirmClick(View view) {
                        final Category category = mCloseCategoryList.get(position);
                        updateCategory(category.getCategoryName(),
                                category.getSort(),
                                STATUS_OPEN,
                                category.getDmId(),
                                new OnUpdateListener() {
                                    @Override
                                    public void updateList() {
                                        Event event = new Event();
                                        event.setData(category);
                                        EventBus.getDefault().post(event);
                                        getActivity().finish();
                                    }

                                },
                                new OnUpdateFailListener() {
                                    @Override
                                    public void updateFail() {
                                        ToastUtil.getInstance().showToast(getActivity(),
                                                "打开分类失败，请稍后重试~");
                                    }
                                },
                                true);
                    }

                    @Override
                    public void onCancelClick(View view) {

                    }
                });
                dialog.show();
            }
        });

        final ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
            @Override
            public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                return makeMovementFlags(ItemTouchHelper.UP | ItemTouchHelper.DOWN, 0);
            }

            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                int fromPosition = viewHolder.getAdapterPosition();
                int toPosition = target.getAdapterPosition();

                if (fromPosition < toPosition) {
                    for (int i = fromPosition; i < toPosition; i++) {
                        Collections.swap(mCategoryList, i, i + 1);
                    }
                } else {
                    for (int i = fromPosition; i > toPosition; i--) {
                        Collections.swap(mCategoryList, i, i - 1);
                    }
                }

                mAdapter.notifyItemMoved(fromPosition, toPosition);
                return true;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {

            }

            @Override
            public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
                super.onSelectedChanged(viewHolder, actionState);
                if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
                    viewHolder.itemView.setBackgroundColor(Color.LTGRAY);
                }
            }

            @Override
            public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                super.clearView(recyclerView, viewHolder);
                viewHolder.itemView.setBackgroundColor(Color.WHITE);
            }
        });
        itemTouchHelper.attachToRecyclerView(mClassificationRecycler);
    }

    @Override
    public void onMenuTextClick() {
        showCategoryDialog(null);
    }

    private void showCategoryDialog(Category category) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        View view = View.inflate(getActivity(), R.layout.dialog_classification, null);
        builder.setView(view);
        final Dialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);

        final OneKeyDeleteEditView editView = (OneKeyDeleteEditView) view.findViewById(R.id.classification_edit);
        TextView dialogTitle = (TextView) view.findViewById(R.id.dialog_title);
        Button confirmBtn = (Button) view.findViewById(R.id.confirm_btn);
        RadioButton openRadioBtn = (RadioButton) view.findViewById(R.id.open_radio_btn);
        RadioButton closeRadioBtn = (RadioButton) view.findViewById(R.id.close_radio_btn);
        ImageView closeIcon = (ImageView) view.findViewById(R.id.close_icon);
        closeIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideKeyboard(editView);
                dialog.dismiss();
            }
        });

        if (category != null) {
            editView.setText(category.getCategoryName());
            if (category.getStatus() == Category.STATUS_CLOSE) {
                closeRadioBtn.setChecked(true);
            } else {
                openRadioBtn.setChecked(true);
            }
            dialogTitle.setText("编辑分类");
        } else {
            openRadioBtn.setChecked(true);
            category = new Category();
            category.setStatus(Category.STATUS_OPEN);
            dialogTitle.setText("添加分类");
        }

        final Category finalCategory = category;
        openRadioBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finalCategory.setStatus(Category.STATUS_OPEN);
            }
        });
        closeRadioBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finalCategory.setStatus(Category.STATUS_CLOSE);
            }
        });
        confirmBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (editView.getText().trim().length() == 0) {
                    ToastUtil.getInstance().showToast(getActivity(), "分类长度不能为空");
                    return;
                }
                if (!TextUtils.isEmpty(finalCategory.getDmId())) {
                    updateCategory(editView.getText(), finalCategory, new OnUpdateListener() {
                        @Override
                        public void updateList() {
                            dialog.dismiss();
                            requestCategoryList();
                        }
                    });
                } else {
                    newCategory(editView.getText(), dialog, finalCategory.getStatus());
                }

            }
        });

        dialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                editView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        SoftInputUtil.get().showSoftInput(mActivity, editView.getInputEditText());
                    }
                }, 300);
            }
        });

        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                SoftInputUtil.get().hideSoftKeyboard(mActivity);
            }
        });

        dialog.show();
    }

    private void updateCategory(String categoryName, int sort, int status, String dmId,
                                final OnUpdateListener onUpdateListener) {
        updateCategory(categoryName, sort, status, dmId, onUpdateListener, null, true);
    }

    /**
     * 更新分类状态
     */
    private void updateCategory(String categoryName, int sort, int status, String dmId,
                                final OnUpdateListener onUpdateListener,
                                final OnUpdateFailListener onUpdateFailListener, boolean isShowLoading) {
        if (isShowLoading) {
            showLoadingDialog();
        }
        mCall = ApiManager.get().getApiService(ApiService.class).updateCategory(categoryName, sort,
                status, dmId);
        HttpRequest.getRequest().autoRecycle(this).start(mCall, new ResponseCallback() {
            @Override
            public void onSuccess(String url, Object data) {
                dismissDialog();
                if (onUpdateListener != null) {
                    onUpdateListener.updateList();
                }
                EventBus.getDefault().post(new EventBean<>(EventBean.STATUS_NEW_CATEGORY));
            }

            @Override
            public void onError(String url, int errorCode, String errorMsg) {
                super.onError(url, errorCode, errorMsg);
                dismissDialog();
                if (onUpdateFailListener != null) {
                    onUpdateFailListener.updateFail();
                }
            }
        });
    }

    private void updateCategory(String categoryName, Category finalCategory, OnUpdateListener onUpdateListener) {
        updateCategory(categoryName, finalCategory.getSort(), finalCategory.getStatus(), finalCategory.getDmId(),
                onUpdateListener);
    }


    private void newCategory(String categoryName, final Dialog dialog, int status) {
        showLoadingDialog();
        mCall = ApiManager.get().getApiService(ApiService.class).newCategory(categoryName,
                getMaxSort(),
                status);
        HttpRequest.getRequest().autoRecycle(this).start(mCall, new ResponseCallback() {
            @Override
            public void onSuccess(String url, Object data) {
                dismissDialog();
                dialog.dismiss();
                requestCategoryList();
            }

            @Override
            public void onError(String url, int errorCode, String errorMsg) {
                super.onError(url, errorCode, errorMsg);
                dismissDialog();
            }
        });
    }

    @Override
    public void editClick(int position, boolean isCheck) {
        if (isCheck) {
            showCategoryDialog(mCategoryList.get(position));
        } else {
            showCategoryDialog(mCloseCategoryList.get(position));
        }

    }

    public int getMaxSort() {
        int maxSort = -1;
        for (int i = 0; i < mCategoryList.size(); i++) {
            if (maxSort < mCategoryList.get(i).getSort()) {
                maxSort = mCategoryList.get(i).getSort();
            }
        }
        // maxSort如果为初始值，那么赋值1，否则加1
        if (maxSort == -1) {
            maxSort = 1;
        } else {
            maxSort++;
        }
        return maxSort;
    }

    private void setSize() {
        mTitleOpen.setText("已开启  (" + mAdapter.getItemCount() + ")");
        mTitleClose.setText("已关闭 (" + mCloseAdapter.getItemCount() + ")");
    }

    /**
     * 仅点击改变状态会回调
     *
     * @param isCheck  改变后的状态
     * @param position 改变的Item位置
     */
    @Override
    public void onCheckedChanged(final boolean isCheck, final int position) {
        int status = isCheck ? Category.STATUS_OPEN : Category.STATUS_CLOSE;
        final Category category;

        if (isCheck) {
            if (position >= 0 && position < mCloseCategoryList.size()) {
                category = mCloseCategoryList.get(position);
            } else {
                ToastUtil.getInstance().showToast(getActivity(), "更新状态失败");
                return;
            }
        } else {
            if (position >= 0 && position < mCategoryList.size()) {
                category = mCategoryList.get(position);
            } else {
                ToastUtil.getInstance().showToast(getActivity(), "更新状态失败");
                return;
            }
        }

        updateCategory(category.getCategoryName(), category.getSort(), status, category.getDmId(),
                new OnUpdateListener() {
                    @Override
                    public void updateList() {
                        updateCategoryStatus(isCheck, position);
                    }
                }, new OnUpdateFailListener() {
                    @Override
                    public void updateFail() {
                        updateCategoryFail(isCheck, position);
                    }
                }, false);
    }

    private void updateCategoryFail(boolean isCheck, int position) {
        if (isCheck) {
            mCloseAdapter.notifyItemChanged(position);
        } else {
            mAdapter.notifyItemChanged(position);
        }
        setSize();
    }

    private void updateCategoryStatus(boolean isCheck, int position) {
        int status = isCheck ? Category.STATUS_OPEN : Category.STATUS_CLOSE;
        Category category;
        if (isCheck) {
            if (position >= 0 && position < mCloseCategoryList.size()) {
                category = mCloseCategoryList.get(position);
                category.setStatus(status);
                mCategoryList.add(category);
                mAdapter.notifyItemInserted(mCategoryList.size());
                mCloseCategoryList.remove(position);
                mCloseAdapter.notifyItemRemoved(position);
            }
        } else {
            if (position >= 0 && position < mCategoryList.size()) {
                category = mCategoryList.get(position);
                category.setStatus(status);
                mCloseCategoryList.add(category);
                mCloseAdapter.notifyItemInserted(mCloseCategoryList.size());
                mCategoryList.remove(position);
                mAdapter.notifyItemRemoved(position);
            }

        }
        setSize();
    }

    interface OnUpdateListener {
        void updateList();
    }

    interface OnUpdateFailListener {
        void updateFail();
    }
}
